package com.scs.application.modules.device.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.scs.application.core.mvc.controller.CrudController;
import com.scs.application.core.query.QueryContext;
import com.scs.application.core.query.QueryContextHolder;
import com.scs.application.modules.device.entity.DeviceLedger;
import com.scs.application.modules.device.entity.DeviceWorkItem;
import com.scs.application.modules.device.mapper.DeviceWorkItemMapper;
import com.scs.application.modules.device.service.DeviceLedgerService;
import com.scs.application.modules.device.service.DeviceWorkItemService;
import com.scs.application.modules.sys.model.PageResult;
import com.scs.application.modules.sys.model.RestResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Map;

/**
 *  设备工作明细表服务层
 */
@RestController
@RequestMapping("/device/work_item")
public class DeviceWorkItemController extends CrudController<DeviceWorkItemService, DeviceWorkItem>{
    @Autowired
    private DeviceLedgerService deviceLedgerService;
    @Autowired
    private DeviceWorkItemMapper deviceWorkItemMapper;

    @PostMapping("/addByScan")
    synchronized public RestResult addByScan(@RequestBody DeviceWorkItem workItem) {
        DeviceLedger ledger = deviceLedgerService.getByDeviceSn(workItem.getDeviceSn());
        BeanUtil.copyProperties(ledger,workItem);
        workItem.setLedgerId(ledger.getId()).setId(null);
        service.saveOrUpdateBatch(Arrays.asList(workItem));
        return RestResult.ok("操作成功");
    }

    /**
     * 列表查询，选择使用
     */
    @GetMapping("/pageSelect")
    public PageResult pageSelect(@RequestParam Map<String, Object> reqData) {
        Map<String, Object> userParam = null;
        //固定参数
        if (reqData.containsKey("userParam")) {
            JSONObject ob = JSON.parseObject(reqData.get("userParam") + "");
            userParam = Maps.newHashMap(ob);
        }

        QueryContext context = QueryContextHolder.currentContext();
        IPage pageResult = deviceWorkItemMapper.pageSelect(context.getPage(), context.getWrapper(), userParam);
        return PageResult.ok("查询成功", pageResult.getRecords(), pageResult.getTotal());
    }


    @PostMapping("/addByScanForCheck")
    synchronized public RestResult addByScanForCheck(@RequestBody DeviceWorkItem workItem) {
        service.addByScanForCheck(workItem);
        return RestResult.ok("操作成功");
    }
}